# -*- coding: utf-8 -*-
'''
Created on 2014/03/03

@author: deadblue
'''

import binascii
import re

def deal(customer, problem):
    p = re.compile(ur'^@[^ ]+ (.+?)[?？](.+)$')
    m = p.match(unicode(problem))
    if m is None: raise '不合法的提问格式'
    # 提取问题和选项
    question = m.group(1)
    options = m.group(2)
    # 拆分选项
    p = re.compile(u'[;；]{1}')
    options = p.split(options)
    return __inner_deal__(customer, question, options)

def __inner_deal__(customer, question, options):
    result = {
              'question' : question,
              'options' : []
              }
    # 计算独立权重和总权重
    total_weight = 0
    for option in options:
        weight = binascii.crc32('%s|%s|%s' % (customer, question, option)) & 0xffffffff
        result['options'].append({
                                  'option' : option,
                                  'weight' : weight
                                  })
        total_weight += weight
    # 按权重排序
    result['options'] = sorted(result['options'], key=lambda x:x['weight'], reverse=True)
    # 计算占比
    score_fix = 10000
    for option in result['options']:
        option['score'] = option['weight'] * 10000 / total_weight
        score_fix -= option['score']
    if score_fix != 0: 
        result['options'][-1]['score'] += score_fix
    return result